package edu.buaa.common.client;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.sql.*;

public abstract class MariaDbExecutorClient extends AbstractSQLClient {
    private final String user = "root";
    private final String password = "langduhua";

    public MariaDbExecutorClient(String serverHost, String dbName, int parallelCnt) throws Exception {
        super(serverHost, dbName, parallelCnt);
    }

    @Override
    protected void createDbIfNotExist(String serverHost, String dbName) throws SQLException, ClassNotFoundException {
        Class.forName("org.mariadb.jdbc.Driver");
        try (Connection conn = DriverManager.getConnection("jdbc:mariadb://" + serverHost + ":3306/", user, password);
             Statement stmt = conn.createStatement()) {
            conn.setAutoCommit(true);
            ResultSet rs = stmt.executeQuery("SELECT * FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = '"+ this.dbName +"'");
            if (!rs.next()) {
                stmt.execute("CREATE DATABASE "+ this.dbName);
                stmt.execute("USE "+ this.dbName);
                for(String q : createTables()){
                    stmt.execute(q);
                }
            }
        }
    }

    @Override
    protected Connection createNormalConnection(String serverHost, String dbName) throws SQLException {
        String dbURL = "jdbc:mariadb://" + serverHost + ":3306/"+dbName;
        return DriverManager.getConnection(dbURL, user, password);
    }

    @Override
    protected void connected(Connection conn) throws Exception{}

    @Override
    public String currentStorageStatus() throws SQLException, InterruptedException {
        Connection conn = connectionPool.take();
        JSONArray arr = new JSONArray();
        try(Statement stmt = conn.createStatement()) {
            conn.setAutoCommit(true);
            ResultSet rs = stmt.executeQuery("select table_name as relname, index_length as indexsize, " +
                    "data_length as tablesize from information_schema.TABLES where table_schema='"+this.dbName+"'");
            while(rs.next()) {
                JSONObject obj = new JSONObject();
                obj.put("relname", rs.getString("relname"));
                obj.put("tablesize", rs.getLong("tablesize"));
                obj.put("indexsize", rs.getLong("indexsize"));
                arr.add(obj);
            }
        }
        connectionPool.put(conn);
        return arr.toJSONString();
    }
}
